package com.chwn.harulib;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;


/**
 * 城市Picker
 * @author zd
 */
public class DatePicker extends LinearLayout {

    /**
     * 滑动控件
     */
    private ScrollerNumberPicker yearPicker;
    private ScrollerNumberPicker monthPicker;
    private ScrollerNumberPicker dayPicker;
    /**
     * 选择监听
     */
    private OnSelectingListener  onSelectingListener;
    /**
     * 刷新界面
     */
    private static final int REFRESH_VIEW = 0x001;
    /**
     * 临时日期
     */

    private              int yearIndex    = 0;
    private              int monthIndex   = 0;
    private              int dayIndex     = 0;
    private Context context;

    /**
     * 所有年
     */
    protected ArrayList<String> yearDatas;
    /**
     * 所有月
     */
    protected ArrayList<String> monthDatas;
    /**
     * /**
     * 所有日
     */
    protected ArrayList<String> dayDatas;


    private Date startDate;
    private Date endDate = new Date();


    private String startDateStr = "2008-01-01";
    private String endDateStr;


    private int startYear;
    private int startMonth;
    private int startDay;
    private int endYear;
    private int endMonth;
    private int endDay;
    // 12个月  还还去除限制

    public DatePicker(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }

    public DatePicker(Context context) {
        super(context);
        this.context = context;
        init();
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_VIEW:
                    if (onSelectingListener != null)
                        onSelectingListener.selected(true);
                    Date selectDate = DatePicker.this.getSelectDate();
                    String week = getWeek_(selectDate);
                    week_tv.setText(week);
                    break;
                default:
                    break;
            }
        }

    };
    private View     week_lin;
    private TextView week_tv;

    private void init() {
        endDateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        LayoutInflater.from(getContext()).inflate(R.layout.city_picker_, this);
        // 获取控件引用
        yearPicker = (ScrollerNumberPicker) findViewById(R.id.province);

        monthPicker = (ScrollerNumberPicker) findViewById(R.id.city);
        dayPicker = (ScrollerNumberPicker) findViewById(R.id.couny);
        week_lin = findViewById(R.id.week_Lin);
        week_tv = (TextView) findViewById(R.id.week_Tv);

        initDate();
    }

    public void setDate(String startDateStr, String endDateStr) {
        this.endDateStr = endDateStr;
        this.startDateStr = startDateStr;
        initDate();
    }

    public void setDate(Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
        initDate();
    }

    private void initDate() {

        yearDatas = new ArrayList<String>();
        monthDatas = new ArrayList<String>();
        dayDatas = new ArrayList<String>();


        if (startDate == null) {
            startDate = stringToDate(startDateStr);
            endDate = stringToDate(endDateStr);
        }


        Calendar cal = Calendar.getInstance();
        cal.setTime(startDate);
        startYear = cal.get(Calendar.YEAR);
        startMonth = cal.get(Calendar.MONTH) + 1;
        startDay = cal.get(Calendar.DAY_OF_MONTH);


        cal.setTime(endDate);

        endYear = cal.get(Calendar.YEAR);
        endMonth = cal.get(Calendar.MONTH) + 1;
        endDay = cal.get(Calendar.DAY_OF_MONTH);

        // 计算年份
        for (int i = startYear; i <= endYear; i++) {
            yearDatas.add(i + "");
        }

        // 12个月  还要去除限制  还要判断是不是最大月
        if (startYear == endYear) {
            for (int i = startMonth; i <= endMonth; i++) {
                monthDatas.add(i + "");
            }
        } else {
            for (int i = startMonth; i <= 12; i++) {
                monthDatas.add(i + "");
            }
        }
        // 获取某年某月有多少天
        // 还要去除限制
        if (startYear == endYear && startMonth == endMonth) {
            for (int i = startDay; i <= endDay; i++) {
                dayDatas.add(i + "");
            }
        } else {
            int maxday = days(startYear, startMonth);
            for (int i = startDay; i <= maxday; i++) {
                dayDatas.add(i + "");
            }
        }


        yearPicker.setData(yearDatas, 1);
        yearPicker.setDefault(0);

        monthPicker.setData(monthDatas, 2);
        monthPicker.setDefault(0);

        dayPicker.setData(dayDatas, 3);
        dayPicker.setDefault(0);
        String week = getWeek_(startDate);
        week_tv.setText(week);
        yearPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

            @Override
            public void endSelect(int id, String text) {
                yearIndex = id;
                // 12个月  还还去除限制
                // 先判断是不是到最小的年  或者到大的年
                monthDatas = new ArrayList<String>();
                if (yearDatas.get(yearIndex).equals(startYear + "")) {
                    if (yearDatas.get(yearIndex).equals(endYear + "")) {
                        for (int i = startMonth; i <= endMonth; i++) {
                            monthDatas.add(i + "");
                        }
                    } else {
                        for (int i = startMonth; i <= 12; i++) {
                            monthDatas.add(i + "");
                        }
                    }

                } else if (yearDatas.get(yearIndex).equals(endYear + "")) {
                    for (int i = 1; i <= endMonth; i++) {
                        monthDatas.add(i + "");
                    }
                } else {
                    for (int i = 1; i <= 12; i++) {
                        monthDatas.add(i + "");
                    }
                }
                // 判断日期是否超过 超过自动减少
                while (monthIndex >= monthDatas.size()) {
                    monthIndex--;
                }

                monthPicker.setData(monthDatas, 2);
                monthPicker.setDefault(monthIndex);

                // 判断日是否过期
                dayDatas = new ArrayList<String>();

                // 选到开始年 开始月 要算天了
                if (yearDatas.get(yearIndex).equals(startYear + "") && monthDatas.get(monthIndex).equals(startMonth + "")) {
                    // 判断是不是开始月和结束月一样
                    if (yearDatas.get(yearIndex).equals(endYear + "") && monthDatas.get(monthIndex).equals(endMonth + "")) {
                        for (int i = startDay; i <= endDay; i++) {
                            dayDatas.add(i + "");
                        }
                    } else {
                        int maxday = days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
                        for (int i = startDay; i <= maxday; i++) {
                            dayDatas.add(i + "");
                        }
                    }

                } else if (yearDatas.get(yearIndex).equals(endYear + "") && monthDatas.get(monthIndex).equals(endMonth + "")) {
                    // 结束年不会和开始年月 在同一天
                    int maxday = days(endYear, endMonth);
                    for (int i = 1; i <= endDay; i++) {
                        dayDatas.add(i + "");
                    }
                } else {
                    int maxday = days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
                    for (int i = 1; i <= maxday; i++) {
                        dayDatas.add(i + "");
                    }
                }
                // 判断日期是否超过 超过自动减少
                while (dayIndex >= dayDatas.size()) {
                    dayIndex--;
                }
                dayPicker.setData(dayDatas, 3);
                dayPicker.setDefault(dayIndex);
                Message message = new Message();
                message.what = REFRESH_VIEW;
                handler.sendMessage(message);
            }

            @Override
            public void selecting(int id, String text) {
            }
        });
        monthPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

            @Override
            public void endSelect(int id, String text) {
                monthIndex = id;
                dayDatas = new ArrayList<String>();
                Message message = new Message();
                message.what = REFRESH_VIEW;
                handler.sendMessage(message);
                // 选到开始年 开始月 要算天了
                if (yearDatas.get(yearIndex).equals(startYear + "") && monthDatas.get(monthIndex).equals(startMonth + "")) {
                    // 判断是不是开始月和结束月一样
                    if (yearDatas.get(yearIndex).equals(endYear + "") && monthDatas.get(monthIndex).equals(endMonth + "")) {
                        for (int i = startDay; i <= endDay; i++) {
                            dayDatas.add(i + "");
                        }
                    } else {
                        int maxday = days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
                        for (int i = startDay; i <= maxday; i++) {
                            dayDatas.add(i + "");
                        }
                    }

                } else if (yearDatas.get(yearIndex).equals(endYear + "") && monthDatas.get(monthIndex).equals(endMonth + "")) {
                    // 结束年不会和开始年月 在同一天
                    int maxday = days(endYear, endMonth);
                    for (int i = 1; i <= endDay; i++) {
                        dayDatas.add(i + "");
                    }
                } else {
                    int maxday = days(Integer.parseInt(yearDatas.get(yearIndex)), Integer.parseInt(monthDatas.get(monthIndex)));
                    for (int i = 1; i <= maxday; i++) {
                        dayDatas.add(i + "");
                    }
                }
                // 判断日期是否超过 超过自动减少
                while (dayIndex >= dayDatas.size()) {
                    dayIndex--;
                }
                dayPicker.setData(dayDatas, 3);
                dayPicker.setDefault(dayIndex);
            }

            @Override
            public void selecting(int id, String text) {

            }
        });
        dayPicker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {

            @Override
            public void endSelect(int id, String text) {
                dayIndex = id;
                Message message = new Message();
                message.what = REFRESH_VIEW;
                handler.sendMessage(message);
            }

            @Override
            public void selecting(int id, String text) {

            }
        });
    }

    private String getWeek_(Date birthDate) {
        if (birthDate == null)
            throw new RuntimeException("出生日期不能为null");
        int age = 0;
        Date now = new Date();
        SimpleDateFormat format_y = new
                SimpleDateFormat("yyyy");
        SimpleDateFormat format_M = new
                SimpleDateFormat("MM");
        String birth_year = format_y.format(birthDate);
        String this_year = format_y.format(now);

        String birth_month = format_M.format(birthDate);
        String this_month = format_M.format(now);

        // 初步，估算
        age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);
        // 如果未到出生月份，则age - 1
        if (this_month.compareTo(birth_month) < 0)
            age -= 1;
        if (age < 0)
            age = 0;
        return age + "岁";
    }

    private String getWeek(Date date) {
        String[] weeks = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    public int days(int year, int month) {
        int days = 0;
        if (month != 2) {
            switch (month) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    days = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;

            }
        } else {
            //闰年
            if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
                days = 29;
            else
                days = 28;

        }
        return days;

    }

    /**
     * string类型转换为date类型
     * @param strTime
     * @return
     */
    public Date stringToDate(String strTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (ParseException e) {
            Log.e("date error", e.toString());
        }
        return date;
    }

    public Date getSelectDate() {
        if (yearDatas.size() - 1 < yearIndex || monthDatas.size() - 1 < monthIndex || dayDatas.size() - 1 < dayIndex) {
            return new Date();
        }
        return stringToDate(yearDatas.get(yearIndex) + "-" + monthDatas.get(monthIndex) + "-" + dayDatas.get(dayIndex));
    }

    public String getSelectDateStr() {
        return new SimpleDateFormat("yyyy-MM-dd").format(getSelectDate());
    }

    public void setOnSelectingListener(OnSelectingListener onSelectingListener) {
        this.onSelectingListener = onSelectingListener;
    }

    public interface OnSelectingListener {
        public void selected(boolean selected);
    }

}